<?php

namespace App\Http\Controllers\Api\v1;


use App\Handlers\KeysHandler;
use App\Models\Configuration;
use App\Models\GoodsOrder;
use App\Models\Shopclick;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class ShopController extends Controller
{

    //店铺统计
    public function statistics(Request $request)
    {
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $type = $request->get('type');

        $nowdate = Carbon::now();
        $nowdatestr = $nowdate->copy()->format('Ymd');

        $yesterday = Carbon::yesterday();
        $yesterdaystr = $yesterday->copy()->format('Ymd');

        $data_order = $data_click = [];
        switch ($type){
            case 'day':
                $data_order =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_ORDER, $type.$nowdatestr, $user->id), $nowdate->copy()->endOfHour(), function ()use($user,$nowdate)  {
                    $now = now();
                    $data_order['order_num'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$nowdate)->where('add_time','<',$now)->count();
                    $data_order['price'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$nowdate)->where('add_time','<',$now)->sum('order_total_price');
                    $data_order['profit'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$nowdate)->where('add_time','<',$now)->sum('order_total_profit');

                    $data_order['order_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$nowdate)->where('add_time','<',$now)->selectRaw('HOUR(created_at) as hour, COUNT(*) as count')->groupBy('hour')->get('hour')->toArray();
                    $data_order['order_list'] = self::setChartDataHour($data_order['order_list'],'hour','count');

                    $data_order['price_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$nowdate)->where('add_time','<',$now)->selectRaw('HOUR(created_at) as hour, SUM(order_total_price) as price')->groupBy('hour')->get()->toArray();
                    $data_order['price_list'] = self::setChartDataHour($data_order['price_list'],'hour','price',1);

                    $data_order['profit_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$nowdate)->where('add_time','<',$now)->selectRaw('HOUR(created_at) as hour, SUM(order_total_profit) as profit')->groupBy('hour')->get()->toArray();
                    $data_order['profit_list'] = self::setChartDataHour($data_order['profit_list'],'hour','profit',1);
                    return $data_order;
                });

                $data_click =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_CLICK, $type, $user->id), KeysHandler::SHOP_STATISTICS_CLICK_TTL, function ()use($user,$nowdate)  {
                    $data_click['click'] = Shopclick::query()->where('user_id','=',$user->id)->whereDate('created_at','=',$nowdate)->sum('click');
                    $data_click['click_list'] = Shopclick::query()->where('user_id','=',$user->id)->whereDate('created_at','=',$nowdate)->selectRaw('HOUR(created_at) as hour, SUM(click) as click')->groupBy('hour')->get()->toArray();
                    $data_click['click_list'] = self::setChartDataHour($data_click['click_list'],'hour','click');
                    return $data_click;
                });
                break;


            case 'yesterday':
                $data_order =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_ORDER, $type.$yesterdaystr, $user->id), $nowdate->copy()->endOfHour(), function ()use($user,$yesterday)  {
                    $now = now();
                    $data_order['order_num'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$yesterday)->count();
                    $data_order['price'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$yesterday)->sum('order_total_price');
                    $data_order['profit'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$yesterday)->sum('order_total_profit');

                    $data_order['order_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$yesterday)->selectRaw('HOUR(created_at) as hour, COUNT(*) as count')->groupBy('hour')->get('hour')->toArray();
                    $data_order['order_list'] = self::setChartDataHour($data_order['order_list'],'hour','count');

                    $data_order['price_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$yesterday)->selectRaw('HOUR(created_at) as hour, SUM(order_total_price) as price')->groupBy('hour')->get()->toArray();
                    $data_order['price_list'] = self::setChartDataHour($data_order['price_list'],'hour','price',1);

                    $data_order['profit_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereDate('add_time','=',$yesterday)->selectRaw('HOUR(created_at) as hour, SUM(order_total_profit) as profit')->groupBy('hour')->get()->toArray();
                    $data_order['profit_list'] = self::setChartDataHour($data_order['profit_list'],'hour','profit',1);
                    return $data_order;
                });

                $data_click =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_CLICK, $type, $user->id), KeysHandler::SHOP_STATISTICS_CLICK_TTL, function ()use($user,$yesterday)  {
                    $data_click['click'] = Shopclick::query()->where('user_id','=',$user->id)->whereDate('created_at','=',$yesterday)->sum('click');
                    $data_click['click_list'] = Shopclick::query()->where('user_id','=',$user->id)->whereDate('created_at','=',$yesterday)->selectRaw('HOUR(created_at) as hour, SUM(click) as click')->groupBy('hour')->get()->toArray();
                    $data_click['click_list'] = self::setChartDataHour($data_click['click_list'],'hour','click');
                    return $data_click;
                });
                break;

            case 'week':
                $startOfWeek = Carbon::now()->startOfWeek(); // 获取本周开始日期
                $endOfWeek = Carbon::now()->endOfWeek();

                $data_order =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_ORDER, $type.$nowdatestr, $user->id), $nowdate->endOfDay(), function ()use($user,$startOfWeek,$endOfWeek)  {
                    $now = now();
                    $data_order['order_num'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereBetween('add_time', [$startOfWeek, $endOfWeek])->where('add_time','<',$now)->count();
                    $data_order['price'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereBetween('add_time', [$startOfWeek, $endOfWeek])->where('add_time','<',$now)->sum('order_total_price');
                    $data_order['profit'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereBetween('add_time', [$startOfWeek, $endOfWeek])->where('add_time','<',$now)->sum('order_total_profit');

                    $data_order['order_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereBetween('add_time', [$startOfWeek, $endOfWeek])->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, COUNT(*) as count')->groupBy('date')->get()->toArray();
                    $data_order['order_list'] = self::setChartDataDay($data_order['order_list'],'date','count',0, $startOfWeek->copy(),'l');

                    $data_order['price_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereBetween('add_time', [$startOfWeek, $endOfWeek])->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, SUM(order_total_price) as price')->groupBy('date')->get()->toArray();
                    $data_order['price_list'] = self::setChartDataDay($data_order['price_list'],'date','price',1, $startOfWeek->copy(),'l');

                    $data_order['profit_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereBetween('add_time', [$startOfWeek, $endOfWeek])->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, SUM(order_total_profit) as profit')->groupBy('date')->get()->toArray();
                    $data_order['profit_list'] = self::setChartDataDay($data_order['profit_list'],'date','profit',1, $startOfWeek->copy(),'l');
                    return $data_order;
                });

                $data_click =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_CLICK, $type, $user->id), KeysHandler::SHOP_STATISTICS_CLICK_TTL, function ()use($user,$startOfWeek,$endOfWeek)  {
                    $data_click['click'] = Shopclick::query()->where('user_id','=',$user->id)->whereBetween('created_at', [$startOfWeek, $endOfWeek])->sum('click');
                    $data_click['click_list'] = Shopclick::query()->where('user_id','=',$user->id)->whereBetween('created_at', [$startOfWeek, $endOfWeek])->selectRaw('DATE(created_at) as date, SUM(click) as click')->groupBy('date')->get()->toArray();
                    $data_click['click_list'] = self::setChartDataDay($data_click['click_list'],'date','click',0, $startOfWeek->copy(),'l');
                    return $data_click;
                });

                break;
            case 'month':
                $startOfMonth = Carbon::now()->startOfMonth();
                $data_order =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_ORDER, $type.$nowdatestr, $user->id), $nowdate->endOfDay(), function ()use($user,$nowdate,$startOfMonth)  {
                    $now = now();
                    $data_order['order_num'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereMonth('add_time','=',$nowdate)->where('add_time','<',$now)->count();
                    $data_order['price'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereMonth('add_time','=',$nowdate)->where('add_time','<',$now)->sum('order_total_price');
                    $data_order['profit'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereMonth('add_time','=',$nowdate)->where('add_time','<',$now)->sum('order_total_profit');

                    $data_order['order_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereMonth('add_time','=',$nowdate)->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, COUNT(*) as count')->groupBy('date')->get()->toArray();
                    $data_order['order_list'] = self::setChartDataDay($data_order['order_list'],'date','count',0, $startOfMonth->copy(),'jS');

                    $data_order['price_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereMonth('add_time','=',$nowdate)->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, SUM(order_total_price) as price')->groupBy('date')->get()->toArray();
                    $data_order['price_list'] = self::setChartDataDay($data_order['price_list'],'date','price',1, $startOfMonth->copy(),'jS');

                    $data_order['profit_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->whereMonth('add_time','=',$nowdate)->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, SUM(order_total_profit) as profit')->groupBy('date')->get()->toArray();
                    $data_order['profit_list'] = self::setChartDataDay($data_order['profit_list'],'date','profit',1, $startOfMonth->copy(),'jS');
                    return $data_order;
                });

                $data_click =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_CLICK, $type, $user->id), KeysHandler::SHOP_STATISTICS_CLICK_TTL, function ()use($user,$nowdate,$startOfMonth)  {
                    $data_click['click'] = Shopclick::query()->where('user_id','=',$user->id)->whereMonth('created_at','=',$nowdate)->sum('click');
                    $data_click['click_list'] = Shopclick::query()->where('user_id','=',$user->id)->whereMonth('created_at','=',$nowdate)->selectRaw('DATE(created_at) as date, SUM(click) as click')->groupBy('date')->get()->toArray();
                    $data_click['click_list'] = self::setChartDataDay($data_click['click_list'],'date','click',0, $startOfMonth->copy(),'jS');
                    return $data_click;
                });

                break;
            case 'all':
                $startOfDay = Carbon::parse($user->created_at);
                $data_order =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_ORDER, $type.$nowdatestr, $user->id), $nowdate->endOfDay(), function ()use($user,$nowdate,$startOfDay)  {
                    $now = now();
                    $data_order['order_num'] = GoodsOrder::query()->where('user_id','=',$user->id)->where('add_time','<',$now)->count();
                    $data_order['price'] = GoodsOrder::query()->where('user_id','=',$user->id)->where('add_time','<',$now)->sum('order_total_price');
                    $data_order['profit'] = GoodsOrder::query()->where('user_id','=',$user->id)->where('add_time','<',$now)->sum('order_total_profit');
                    $data_order['order_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, COUNT(*) as count')->groupBy('date')->get()->toArray();
                    $data_order['order_list'] = self::setChartDataDay($data_order['order_list'],'date','count',0, $startOfDay->copy(),'Md');

                    $data_order['price_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, SUM(order_total_price) as price')->groupBy('date')->get()->toArray();
                    $data_order['price_list'] = self::setChartDataDay($data_order['price_list'],'date','price',1, $startOfDay->copy(),'Md');

                    $data_order['profit_list'] = GoodsOrder::query()->where('user_id','=',$user->id)->where('add_time','<',$now)->selectRaw('DATE(created_at) as date, SUM(order_total_profit) as profit')->groupBy('date')->get()->toArray();
                    $data_order['profit_list'] = self::setChartDataDay($data_order['profit_list'],'date','profit',1, $startOfDay->copy(),'Md');
                    return $data_order;
                });

                $data_click =  Cache::remember(sprintf(KeysHandler::SHOP_STATISTICS_CLICK, $type, $user->id), KeysHandler::SHOP_STATISTICS_CLICK_TTL, function ()use($user,$nowdate,$startOfDay)  {
                    $data_click['click'] = Shopclick::query()->where('user_id','=',$user->id)->sum('click');
                    $data_click['click_list'] = Shopclick::query()->where('user_id','=',$user->id)->selectRaw('DATE(created_at) as date, SUM(click) as click')->groupBy('date')->get()->toArray();
                    $data_click['click_list'] = self::setChartDataDay($data_click['click_list'],'date','click',0, $startOfDay->copy(),'Md');
                    return $data_click;
                });

                break;
            default:
                $data_order['order_num'] = $data_order['price'] = $data_order['profit'] = $data_click['click'] = 0;
                $data_order['order_list'] = $data_order['price_list'] = $data_order['profit_list'] = $data_click['click_list']  = [];
                break;
        }

        $data = array_merge($data_order , $data_click);
        return $this->success($data);
    }


    public function setChartDataHour($list,$x,$y,$isAmount = 0){
        $relist = [];
        $nowdate = Carbon::now();
        for ($h = 0; $h <= $nowdate->format('h'); $h++){
            $dataY = 0;
            foreach ($list as $val){
                if($val[$x] == $h){
                    $dataY = $isAmount == 1 ? bcdiv($val[$y],100) : $val[$y];
                }
            }
            $relist['dataX'][] = $h;
            $relist['dataY'][] = $dataY;
        }
        return $relist;
    }

    public function setChartDataDay($list,$x,$y,$isAmount,$start,$f){
        $relist = [];
        $start = Carbon::parse($start->format('Y-m-d'));
        $nowdate = Carbon::now()->format('Y-m-d');
        for ($d = $start; $d->lte($nowdate); $d->addDay()){
            $dataY = 0;
            foreach ($list as $val){
                if(Carbon::parse($val[$x])->eq($d)){
                    $dataY = $isAmount == 1 ? bcdiv($val[$y],100) : $val[$y];
                }
            }
            $relist['dataX'][] = $d->format($f);
            $relist['dataY'][] = $dataY;
        }
        return $relist;
    }



}
